/**
 *    Copyright (C) 2007-2009 DIVIS GmbH (http://www.divis-hagen.de/)
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation; either
 *    version 3 of the License, or (at your option) any later version.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General
 *    Public License along with this library; if not, write to the
 *    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *    Boston, MA 02110-1301 USA
 */

package de.divis_hagen.json.rs;

import de.divis_hagen.json.JSONContext;
import de.divis_hagen.json.JSONException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.annotation.XmlRootElement;


/**
 * <p>
 * This body-writer uses Aeson to marshall objects to json. This is a more direct approach compared
 * to the usual object -> xml -> json way of marshalling and retains all meta-data from the class
 * during the marshalling process.
 * </p>
 * 
 * @author Aike J Sommer
 */
@Produces("application/json")
@Provider()
public class AesonBodyWriter implements MessageBodyWriter<Object> {

    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] methodAnnotations,
            MediaType mediaType) {
        return type.isAnnotationPresent(XmlRootElement.class);
    }

    public long getSize(Object t,
            Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    public void writeTo(Object t,
            Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException,
            WebApplicationException {
        JSONContext context = JSONContext.newInstance(t.getClass());
        context.setUnwrap(true);
        context.setEscapeNames(true);
        try {
            context.createMarshaller().marshall(t, entityStream);
            entityStream.close();
        } catch (JSONException ex) {
            throw new WebApplicationException(ex);
        }
    }

}
